package top.v5it.japi.ddd.example.member.service.impl;

import cn.hutool.core.lang.Assert;
import org.springframework.stereotype.Service;
import top.v5it.japi.ddd.core.dao.impl.BasicDaoJdbcImpl;
import top.v5it.japi.ddd.core.repository.CacheEntityDao;
import top.v5it.japi.ddd.core.service.impl.BasicServiceImpl;
import top.v5it.japi.ddd.example.member.entity.Member;
import top.v5it.japi.ddd.example.member.entity.MemberLevel;
import top.v5it.japi.ddd.example.member.service.MemberLevelService;

import java.util.Comparator;
import java.util.List;

/**
 * @author zhanpu
 * @date 2023/11/9
 */
@Service(MemberLevelService.SERVICE_NAME)
public class MemberLevelServiceImpl extends BasicServiceImpl<CacheEntityDao> implements MemberLevelService {
    @Override
    public void add(MemberLevel entity) {
        Assert.notNull(entity, "请求参数[entity]不能为空");
        basicDao.insert(entity);
    }

    @Override
    public void modify(MemberLevel entity) {
        Assert.notNull(entity, "请求参数[entity]不能为空");
        basicDao.update(entity);
    }

    @Override
    public MemberLevel searchById(Long id) {
        Assert.notNull(id, "请求id不能为空");
        return basicDao.load(id, new MemberLevel());
    }

    /**
     * 根据积分计算会员等级
     *
     * @param totalPoints
     * @return
     */
    @Override
    public MemberLevel cacLevel(Integer totalPoints) {
        final List<MemberLevel> memberLevels = basicDao.loadAll(new MemberLevel());
        // 最高等级排序
        memberLevels.sort(Comparator.comparing(MemberLevel::getMin_points).reversed());
        for (MemberLevel memberLevel : memberLevels) {
            if (memberLevel.getMin_points().compareTo(totalPoints) <= 0) {
                return memberLevel;
            }
        }
        return new MemberLevel();
    }
}
